import { Avatar, Menu, Spin } from 'antd';
import { LogoutOutlined, SettingOutlined, UserOutlined } from '@ant-design/icons';
import React, { useCallback } from 'react';
import { history, useModel } from 'umi';

import HeaderDropdown from '../HeaderDropdown';
import type { MenuInfo } from 'rc-menu/lib/interface';
import { postApiLogout as outLogin } from '@/services/furion-cms/Account';
import { stringify } from 'querystring';
import styles from './index.less';

export type GlobalHeaderRightProps = {
  menu?: boolean;
};

const loginPath = '/admin/login';

/**
 * 退出登录，并且将当前的 url 保存
 */
const loginOut = () => {
  const { query = {}, pathname } = history.location;
  const { redirect } = query;
  // Note: There may be security issues, please note
  if (window.location.pathname !== loginPath && !redirect) {
    history.replace({
      pathname: loginPath,
      search: stringify({
        redirect: pathname,
      }),
    });
  }

  // TODO:关闭监听未实现

  return outLogin({
    skipErrorHandler: false
  }).then(() => {
    // 清除本地存储
    localStorage.removeItem("access-token");
    localStorage.removeItem("x-access-token");
  });
};

const AvatarDropdown: React.FC<GlobalHeaderRightProps> = ({ menu }) => {
  const { initialState, setInitialState } = useModel('@@initialState');

  const onMenuClick = useCallback(
    (event: MenuInfo) => {
      const { key } = event;
      if (key === 'logout') {
        initialState?.eventHub?.Instance?.close(); //关闭服务端事件监听
        setInitialState((s) => ({ ...s, currentUser: undefined, eventHub: undefined }));
        loginOut();
        return;
      }
      history.push(`/admin/account/${key}`);
    },
    [setInitialState],
  );

  const loading = (
    <span className={`${styles.action} ${styles.account}`}>
      <Spin
        size="small"
        style={{
          marginLeft: 8,
          marginRight: 8,
        }}
      />
    </span>
  );

  if (!initialState) {
    return loading;
  }

  const { currentUser } = initialState;

  if (!currentUser || !currentUser.nickName) {
    return loading;
  }

  const menuHeaderDropdown = (
    <Menu className={styles.menu} selectedKeys={[]} onClick={onMenuClick}>
      {menu && (
        <Menu.Item key="center">
          <UserOutlined />
          个人中心
        </Menu.Item>
      )}
      {menu && (
        <Menu.Item key="settings">
          <SettingOutlined />
          个人设置
        </Menu.Item>
      )}
      {menu && <Menu.Divider />}

      <Menu.Item key="logout">
        <LogoutOutlined />
        退出登录
      </Menu.Item>
    </Menu>
  );
  return (
    <HeaderDropdown overlay={menuHeaderDropdown}>
      <span className={`${styles.action} ${styles.account}`}>
        <Avatar size="small" className={styles.avatar} src={currentUser.avatar} alt="avatar" icon={<UserOutlined />} />
        <span className={`${styles.name} anticon`}>{currentUser.nickName}</span>
      </span>
    </HeaderDropdown>
  );
};

export default AvatarDropdown;
